#include "screenshotwindow.h"
#include "sizehandle.h"

#include <QApplication>
#include <QGuiApplication>
#include <QKeyEvent>
#include <QPainter>
#include <QDesktopWidget>
#include <QScreen>
#include <QClipboard>
#include <QDebug>

ScreenshotWindow::ScreenshotWindow(QWidget *parent) :
    QDialog(parent),
    m_cursorShape(Qt::ArrowCursor),
    m_picture(this),
//    m_selectRect(0, 0, 0, 0),
    m_mousePressPos(0, 0),
    m_mouseReleasePos(0, 0),
    m_mouseCurPos(0, 0),
    m_cursorMode(None),
    m_screenshotTool(this),
    m_drawLineProperty(&m_screenshotTool, CDrawProperty::Line, this),
    m_drawRectProperty(&m_screenshotTool, CDrawProperty::rect, this),
    m_drawTextProperty(&m_screenshotTool, CDrawProperty::text, this),
    m_curDir(0),
    m_bLeftButtonPress(false),
    m_pShape(nullptr),
    m_nShape(),
    m_colorPicker(this),
    m_curQuadrant(PosQuadrant::rightBottom),
    m_nUpdateTimer(-1)
{
    init();
}

ScreenshotWindow::~ScreenshotWindow()
{
    if (m_nUpdateTimer >= 0)
    {
        killTimer(m_nUpdateTimer);
    }
}

void ScreenshotWindow::showScreen()
{
    QList<QScreen *> screens = QGuiApplication::screens();
    for (int i=0; i<screens.size(); ++i)
    {
        QScreen *pScreen = screens.at(i);
        if (pScreen)
        {
            QRect screenRect = pScreen->geometry();
            QPixmap pixmap = pScreen->grabWindow(0);
            QPainter painter(&m_screenWindow.screenPixmap);
            painter.drawPixmap(screenRect, pixmap);

            QPainter painterBG(&m_screenWindow.screenPixmapBackGround);
            painterBG.drawPixmap(screenRect, pixmap);

//            screenWindow sw;
//            sw.screenRect = screenRect;
//            sw.screenPixmap = pixmap;
//            sw.screenPixmapBackGround = pixmap;
//            //模糊背景
//            QPainter paint(&m_screenWindow.screenPixmapBackGround);
//            paint.fillRect(m_screenWindow.screenPixmapBackGround.rect(), QBrush(QColor(160, 160, 160, 100)));

//            QPainter paint1(&m_screenWindow.screenPixmap);
//            paint1.fillRect(m_screenWindow.screenPixmap.rect(), QBrush(QColor(255, 255, 160, 255)));
            //m_screenWindows.append(m_screenWindow);
        }
    }

    //模糊背景
    QPainter paint(&m_screenWindow.screenPixmapBackGround);
    paint.fillRect(m_screenWindow.screenPixmapBackGround.rect(), QBrush(QColor(160, 160, 160, 100)));

    show();
}

QRect ScreenshotWindow::FillShape()
{
    QPainter paintPixmap(&m_paintPixmap);
    //for (int i=0; i<m_screenWindows.size(); ++i)
    {
        QPainter fullPainter(&m_screenWindow.screenPixmap);
        const int nSize = m_Shapes.size();
        if (nSize > 0)
        {
            for (int i=0; i<nSize; ++i)
            {
                Shape* pShape = m_Shapes.at(i);
                if (pShape)
                {
                    pShape->Paint(&fullPainter);
                }
            }
        }
        QRect rectScreen;
        screenWindow sw = m_screenWindow;
        int width = sw.screenRect.width();
        int height = sw.screenRect.height();
        rectScreen.setTopLeft(mapFromGlobal(sw.screenRect.topLeft()));
        rectScreen.setWidth(width);
        rectScreen.setHeight(height);
        //painter.drawPixmap(rectScreen, sw.screenPixmapBackGround);
        QRect intersectionRect = m_picture.rect() & rectScreen;
        if (!intersectionRect.isNull() || intersectionRect.isValid() || !intersectionRect.isEmpty())
        {
            //截图在图片中大小
            QRect pixmapRect(intersectionRect.topLeft()-rectScreen.topLeft(), intersectionRect.size());
            //原有画在widget上的
//                painter.drawPixmap(intersectionRect, sw.screenPixmap.copy(pixmapRect));
            //画在pixmap上的
            QRect paintPixmapRect(intersectionRect.x()-m_picture.rect().x(),\
                                  intersectionRect.y()-m_picture.rect().y(),\
                                  intersectionRect.width(), intersectionRect.height());
            paintPixmap.drawPixmap(paintPixmapRect, sw.screenPixmap.copy(pixmapRect));
            return intersectionRect;
        }
    }

    return QRect();
}

QString ScreenshotWindow::getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options)
{
    const QStringList schemes = QStringList(QStringLiteral("file"));
    const QUrl selectedUrl = getSaveFileUrl(parent, caption, QUrl::fromLocalFile(dir), filter,
                                            selectedFilter, options, schemes);
    if (selectedUrl.isLocalFile() || selectedUrl.isEmpty())
        return selectedUrl.toLocalFile();
    else
        return selectedUrl.toString();
}

QUrl ScreenshotWindow::getSaveFileUrl(QWidget *parent, const QString &caption, const QUrl &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options, const QStringList &supportedSchemes)
{
    QFileDialog dialog(parent, caption, dir.toString(), filter);
    dialog.setAttribute(Qt::WA_QuitOnClose, false);
    dialog.setFileMode(QFileDialog::AnyFile);
    dialog.setSupportedSchemes(supportedSchemes);
    dialog.setAcceptMode(QFileDialog::AcceptSave);
    dialog.setOptions(options);
    if (selectedFilter && !selectedFilter->isEmpty())
        dialog.selectNameFilter(*selectedFilter);
    if (dialog.exec() == QDialog::Accepted) {
        if (selectedFilter)
            *selectedFilter = dialog.selectedNameFilter();
        return dialog.selectedUrls().value(0);
    }
    return QUrl();
}

void ScreenshotWindow::screenshotToolShow(bool b)
{
    if (b)
    {
        m_screenshotTool.show();
        m_screenshotTool.move(adjustScreenshotToolPos());
        CDrawProperty::ShowCurrentWindow();
    }
    else {
        m_screenshotTool.hide();
        CDrawProperty::HideCurrentWindow();
    }
}

void ScreenshotWindow::screenshotDone(bool toClipBoard)
{
    if (toClipBoard)
    {
        FillShape();
        QClipboard *board = QApplication::clipboard();
        board->setPixmap(m_paintPixmap);
    }

    close();
}

void ScreenshotWindow::savePicture()
{
    QString qsDefault = QCoreApplication::applicationDirPath();

    QString qsSelectedFilter;
    QString fileName = getSaveFileName(this,
          tr("保存图像"), qsDefault, tr("JPG (*.jpg);;JPEG (*.jpeg);;PNG (*.png);;BMP (*.bmp)"), &qsSelectedFilter);

    QString qsImageFormat;
    if (qsSelectedFilter.contains(QString("JPG")))
    {
        qsImageFormat = "JPG";
    }
    else if (qsSelectedFilter.contains(QString("JPEG")))
    {
        qsImageFormat = "JPEG";
    }
    else if (qsSelectedFilter.contains(QString("PNG")))
    {
        qsImageFormat = "PNG";
    }
    else if (qsSelectedFilter.contains(QString("BMP")))
    {
        qsImageFormat = "BMP";
    }

    if (!fileName.isEmpty())
    {
        FillShape();
        m_paintPixmap.save( fileName, (qsImageFormat.isEmpty() ? nullptr : qsImageFormat.toStdString().c_str()) );
    }
    close();
}

void ScreenshotWindow::pasteOnTheScreen()
{
    QRect rect = FillShape();
    emit pasteOnTheScreen(m_paintPixmap, rect);
    close();
}

void ScreenshotWindow::drawNone()
{
    m_cursorMode = None;
    //qDebug() << "ScreenshotWindow::drawNone m_cursorMode=" << m_cursorMode;
    m_nShape = Shape::none;
    if (CDrawProperty::HideCurrentWindow())
    {
        CDrawProperty::SetCurrentPropertyPtr(nullptr);
    }
}

void ScreenshotWindow::drawRect()
{
    m_cursorMode = Draw;
    //qDebug() << "ScreenshotWindow::drawRect set cursorMode=" << m_cursorMode;
    m_nShape = Shape::rect;
    CDrawProperty::HideCurrentWindow();
    CDrawProperty::SetCurrentPropertyPtr(&m_drawRectProperty);
    //m_drawRectProperty.ShowWidgetAndHideOtherGroupWidget();
    m_drawRectProperty.show();
}

void ScreenshotWindow::drawText()
{
    m_cursorMode = Draw;
    m_nShape = Shape::text;
    CDrawProperty::HideCurrentWindow();
    CDrawProperty::SetCurrentPropertyPtr(&m_drawTextProperty);
    //m_drawTextProperty.ShowWidgetAndHideOtherGroupWidget();
    m_drawTextProperty.show();
}

void ScreenshotWindow::drawLine()
{
    m_cursorMode = Draw;
    m_nShape = Shape::line;
    CDrawProperty::HideCurrentWindow();
    CDrawProperty::SetCurrentPropertyPtr(&m_drawLineProperty);
    m_drawLineProperty.show();
    //m_Shape = new Line(this);
    //m_drawLineProperty.ShowWidgetAndHideOtherGroupWidget();
}

void ScreenshotWindow::drawLineWithArrow()
{

}

void ScreenshotWindow::drawShape(ScreenshotTool::shape shape)
{
    switch (shape) {
    case ScreenshotTool::shape::None:
        drawNone();
        break;
    case ScreenshotTool::shape::Line:
        drawLine();
        break;
    case ScreenshotTool::shape::Rect:
        drawRect();
        break;
    case ScreenshotTool::shape::Text:
        drawText();
        break;
    default:
        break;
    }
}

void ScreenshotWindow::PropertyChange(const DRAWPROPERTY &property)
{
    m_property = property;
}

void ScreenshotWindow::Undo()
{
    //将链表最后一个取出放到undo链表
    if (m_Shapes.size())
    {
        m_undoStack.push(m_Shapes.takeLast());
        m_screenshotTool.EnableRedo(true);
    }
    if (m_Shapes.isEmpty())
    {
        m_screenshotTool.EnableUndo(false);
    }
    update();
}

void ScreenshotWindow::Redo()
{
    if (!m_undoStack.isEmpty())
    {
        m_Shapes.push_back(m_undoStack.pop());
        m_screenshotTool.EnableUndo(true);
    }

    if (m_undoStack.isEmpty())
    {
        m_screenshotTool.EnableRedo(false);
    }
    else
    {
        m_screenshotTool.EnableRedo(true);
    }

    update();
}

void ScreenshotWindow::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == m_nUpdateTimer)
    {
        update();
    }
    QDialog::timerEvent(event);
}

bool ScreenshotWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (&m_screenshotTool == watched || watched->objectName() == "CColorPanel")
    {
        if (event->type() == QEvent::Leave)
        {
            if (m_picture.rect().isNull())
            {
                m_colorPicker.setVisible(true);
            }
        }
        else if (event->type() == QEvent::Enter)
        {
            m_colorPicker.setVisible(false);
        }
    }

    return QDialog::eventFilter(watched, event);
}

void ScreenshotWindow::mousePressEvent(QMouseEvent *event)
{
    if (!event)
    {
        return;
    }
    setFocus();
    //m_colorPicker.setVisible(false);
    switch (event->button()) {
    case Qt::RightButton:
        m_picture.setRect(QRect());
//        m_picture.setSize(QSize(0, 0));
        m_cursorMode = None;
        //qDebug() << "ScreenshotWindow::mousePressEvent 1 m_cursorMode=" << m_cursorMode;
        break;
    case Qt::LeftButton:
        m_mousePressPos = event->pos();
        //qDebug() << "ScreenshotWindow::mousePressEvent 2 m_cursorMode=" << m_cursorMode;
        if (None == m_cursorMode)
        {
            if (m_picture.rect().isEmpty())
            {
                m_cursorMode = Select;
                m_topLeft = m_mousePressPos;
            }
        }
        m_bLeftButtonPress = true;
        if (Draw == m_cursorMode)
        {
            TextEditComplete();
            //qDebug() << "ScreenshotWindow::mousePressEvent 3 m_nShape=" << m_nShape;
            m_pShape = createShape(m_nShape);
            if (m_pShape)
            {
                m_Shapes.push_back(m_pShape);
                m_pShape->SetStartPoint(event->pos());
                m_screenshotTool.EnableUndo(true);
            }
        }
        break;
    default:
        break;
    }
    update();
    emit screenshotToolWidgetShow(false);
    m_colorPicker.setVisible(false);
    QDialog::mousePressEvent(event);
}

void ScreenshotWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (m_picture.rect().isNull())
    {
        m_colorPicker.setVisible(true);
    }
    QDialog::mouseReleaseEvent(event);
    switch (event->button()) {
    case Qt::RightButton:
        m_mouseReleasePos = m_mousePressPos;
        TextEditComplete();
        break;
    case Qt::LeftButton:
        m_mouseReleasePos = event->pos();
        m_bLeftButtonPress = false;
        break;
    default:
        break;
    }
    emit screenshotToolWidgetShow();
    if (m_mouseReleasePos == m_mousePressPos)
    {
        return;
    }
    if (Select == m_cursorMode)
    {
        calcRectPoint(m_topLeft);
        m_picture.setRect(QRect(m_topLeft.x(), m_topLeft.y(), \
                             abs(m_mouseReleasePos.x()-m_mousePressPos.x()), \
                             abs(m_mouseReleasePos.y()-m_mousePressPos.y())));
    }
    update();
    if (Draw != m_cursorMode)
    {
        m_cursorMode = None;
    }
}

void ScreenshotWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
    QDialog::mouseDoubleClickEvent(event);
}

void ScreenshotWindow::mouseMoveEvent(QMouseEvent *event)
{
    QDialog::mouseMoveEvent(event);
    m_mouseCurPos = event->pos();
    m_colorPicker.Move(mapToGlobal(event->pos()), CheckPickerPos(event->pos()));
    if (m_bLeftButtonPress)
    {
        if (Select == m_cursorMode)
        {
            //清空shape
            foreach (auto iter, m_Shapes) {
                delete iter;
            }
            m_Shapes.clear();
            m_mouseReleasePos = event->pos();
            calcRectPoint(m_topLeft);
            m_picture.setRect(QRect(m_topLeft.x(), m_topLeft.y(), \
                                 abs(m_mouseReleasePos.x()-m_mousePressPos.x()), \
                                 abs(m_mouseReleasePos.y()-m_mousePressPos.y())));
        }
        else if (Size == m_cursorMode)
        {
            m_picture.resize(m_curDir, event->pos() - m_mousePressPos);
        }
        else if (Move == m_cursorMode)
        {
            m_topLeft = m_picture.move(event->pos() - m_mousePressPos);
        }
        else if (Draw == m_cursorMode)
        {
            if (m_pShape)
            {
                m_pShape->SetEndPoint(event->pos());
            }
        }
    }
    else
    {
        {
            if (Draw == m_cursorMode)
            {
                if (ScreenshotTool::Text == m_nShape)
                {
                    setCursor(Qt::IBeamCursor);
                }
                else
                {
                    setCursor(Qt::CrossCursor);
                }
                return;
            }
            m_curDir = 0;
            int nMode = detectCusor(event->pos(), m_curDir);
            switch (nMode) {
            case Size:
            {
                switch (m_curDir) {
                case SizeHandle::Left:
                case SizeHandle::Right:
                    setCursor(Qt::SizeHorCursor);
                    m_cursorMode = Size;
                    break;
                case SizeHandle::Top:
                case SizeHandle::Bottom:
                    setCursor(Qt::SizeVerCursor);
                    m_cursorMode = Size;
                    break;
                case SizeHandle::LeftTop:
                case SizeHandle::RightBottom:
                    setCursor(Qt::SizeFDiagCursor);
                    m_cursorMode = Size;
                    break;
                case SizeHandle::LeftBottom:
                case SizeHandle::RightTop:
                    m_cursorMode = Size;
                    setCursor(Qt::SizeBDiagCursor);
                    break;
                }
            }
                break;
            case Move:
                m_cursorMode = Move;
                setCursor(Qt::SizeAllCursor);
                break;
            default:
                //qDebug() << "ScreenshotWindow::mouseMoveEvent m_cursorMode=" << m_cursorMode;
                //m_cursorMode = None;
                //setCursor(Qt::CrossCursor);
                break;
            }
        }
    }
    update();
}

void ScreenshotWindow::keyPressEvent(QKeyEvent *event)
{
    if (m_pShape && m_pShape->Type() == Shape::text && Qt::Key_Escape != event->key())
    {
        LineText *pText = static_cast<LineText*>(m_pShape);
        //移动光标
        switch (event->key()) {
            case Qt::Key_Left:
                pText->MoveCursor(-1);
                break;
            case Qt::Key_Right:
                pText->MoveCursor(1);
                break;
            case Qt::Key_Backspace:
                pText->BackSpace();
                break;
            case Qt::Key_Delete:
                pText->Delete();
                break;
            case Qt::Key_Home:
                pText->Home();
                break;
            case Qt::Key_End:
                pText->End();
                break;
        }
#ifdef Q_OS_WIN
        if(event->text().length() > 0 && event->text().at(0).isPrint()) {
            pText->AppendText(event->text().at(0));
        }
#endif
        update();
        return;
    }
    switch (event->key()) {
        case Qt::Key_Escape:
            close();
            break;
        case Qt::Key_Up:
            //鼠标位置向上移动一像素
            QCursor::setPos(QPoint(m_mouseCurPos.x(), m_mouseCurPos.y() - 1));
            break;
        case Qt::Key_Down:
            QCursor::setPos(QPoint(m_mouseCurPos.x(), m_mouseCurPos.y() + 1));
            break;
        case Qt::Key_Left:
            QCursor::setPos(QPoint(m_mouseCurPos.x() - 1, m_mouseCurPos.y()));
            break;
        case Qt::Key_Right:
            QCursor::setPos(QPoint(m_mouseCurPos.x() + 1, m_mouseCurPos.y()));
            break;
    }
    update();
}

void ScreenshotWindow::showEvent(QShowEvent *event)
{
    if(this->focusWidget()){
        this->focusWidget()->clearFocus();
    }
    this->setFocus();
    QDialog::showEvent(event);
}

void ScreenshotWindow::enterEvent(QEvent *event)
{
    QDialog::enterEvent(event);
    setCursor(Qt::CrossCursor);
    const QPoint pos = QCursor::pos();
    m_colorPicker.Move(mapToGlobal(pos), CheckPickerPos(pos));
    if (m_picture.rect().isNull())
    {
        m_colorPicker.show();
    }
}

void ScreenshotWindow::leaveEvent(QEvent *event)
{
    QDialog::leaveEvent(event);
    setCursor(Qt::ArrowCursor);
    m_colorPicker.hide();
}

void ScreenshotWindow::paintEvent(QPaintEvent *event)
{
    QDialog::paintEvent(event);

    QPainter painter(this);
    QRect rectScreen;
    screenWindow sw = m_screenWindow;
    int width = sw.screenRect.width();
    int height = sw.screenRect.height();
    rectScreen.setTopLeft(mapFromGlobal(sw.screenRect.topLeft()));
    rectScreen.setWidth(width);
    rectScreen.setHeight(height);
    //if (m_screenWindows.size() > 0)
    {
        painter.drawPixmap(rectScreen, sw.screenPixmapBackGround);
        QPixmap pixmap(m_picture.rect().size());
        if (!pixmap.isNull())
        {
            QPainter paintPixmap(&pixmap);
            //for (int i=0; i<m_screenWindows.size(); ++i)
            {
                QRect intersectionRect = m_picture.rect() & rectScreen;
                if (!intersectionRect.isNull() || intersectionRect.isValid() || !intersectionRect.isEmpty())
                {
                    //截图在图片中大小
                    QRect pixmapRect(intersectionRect.topLeft()-rectScreen.topLeft(), intersectionRect.size());
                    //原有画在widget上的
    //                painter.drawPixmap(intersectionRect, sw.screenPixmap.copy(pixmapRect));
                    //画在pixmap上的
                    QRect paintPixmapRect(intersectionRect.x()-m_picture.rect().x(),\
                                          intersectionRect.y()-m_picture.rect().y(),\
                                          intersectionRect.width(), intersectionRect.height());
                    paintPixmap.drawPixmap(paintPixmapRect, sw.screenPixmap.copy(pixmapRect));
                }
            }
            m_paintPixmap = pixmap;
            painter.drawPixmap(m_picture.rect(), pixmap);
        }
    }
    m_picture.paint(&painter);
    const int nSize = m_Shapes.size();
    if (nSize > 0)
    {
        for (int i=0; i<nSize; ++i)
        {
            Shape* pShape = m_Shapes.at(i);
            if (pShape)
            {
                pShape->Paint(&painter);
            }
        }
    }
    // 绘制中心十字线
//     painter.save();
//     painter.setPen(QPen(Qt::black, 2));
// //            int centerX = rectScreen.left() + halfSize;
// //            int centerY = rectScreen.top() + halfSize;
//     painter.drawLine(0, m_mouseCurPos.y(), rectScreen.width(), m_mouseCurPos.y());
//     painter.drawLine(m_mouseCurPos.x(), 0, m_mouseCurPos.x(), rectScreen.height());
//     painter.restore();
}

QVariant ScreenshotWindow::inputMethodQuery(Qt::InputMethodQuery query) const
{
    if (m_pShape && m_pShape->Type() == Shape::text)
    {
        LineText *pLineText = static_cast<LineText*>(m_pShape);
        switch(query) {
        case Qt::ImEnabled:
            return true; // 输入法启用
        case Qt::ImCursorRectangle:
        {
            return pLineText->TextRect();
        }
        case Qt::ImAnchorRectangle:
            return pLineText->TextRect();
        case Qt::ImFont:
            return pLineText->Font();
        case Qt::ImCursorPosition: {
            return QVariant(pLineText->CursorPositon()); }
        case Qt::ImSurroundingText:
            return QVariant(pLineText->Text());
//        case Qt::ImCurrentSelection:
//            return QVariant(selectedText());
        case Qt::ImMaximumTextLength:
            return QVariant();
        case Qt::ImAnchorPosition:
            return QVariant(pLineText->CursorPositon());
        case Qt::ImHints:
            return Qt::ImhNone; // 输入法提示
        case Qt::ImPreferredLanguage:
            return QLocale::system().name(); // 系统语言
        default:
            return QWidget::inputMethodQuery(query);
        }
    }
    return QVariant();
}

void ScreenshotWindow::inputMethodEvent(QInputMethodEvent *event)
{
    if (m_pShape && m_pShape->Type() == Shape::text)
    {
        LineText *pLineText = static_cast<LineText*>(m_pShape);
        if (!event->commitString().isEmpty())
        {
            pLineText->AppendText(event->commitString());
            update();
        }
    }

    QDialog::inputMethodEvent(event);
}

void ScreenshotWindow::init()
{
    //置顶
#ifndef DEBUG
    setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Popup);
#endif
    setAttribute(Qt::WA_InputMethodEnabled);
    //设置全屏
    setGeometry(QApplication::desktop()->geometry());
    m_screenWindow.screenRect = QApplication::desktop()->geometry();
    m_screenWindow.screenPixmap = QPixmap(QApplication::desktop()->geometry().width(), QApplication::desktop()->geometry().height());
    m_screenWindow.screenPixmapBackGround = QPixmap(QApplication::desktop()->geometry().width(), QApplication::desktop()->geometry().height());
    setAttribute(Qt::WA_QuitOnClose, false);
    setMouseTracking(true);
    showScreen();
    connect(this, &ScreenshotWindow::screenshotToolWidgetShow, \
            &ScreenshotWindow::screenshotToolShow);
    connect(&m_screenshotTool, &ScreenshotTool::screenshotComplete, this, &ScreenshotWindow::screenshotDone);
    connect(&m_screenshotTool, &ScreenshotTool::pasteOnTheScreen, this, QOverload<>::of(&ScreenshotWindow::pasteOnTheScreen));
    connect(&m_screenshotTool, &ScreenshotTool::drawShape, this, &ScreenshotWindow::drawShape);
    connect(&m_screenshotTool, &ScreenshotTool::saveScreenshot, this, QOverload<>::of(&ScreenshotWindow::savePicture));
    connect(&m_screenshotTool, &ScreenshotTool::Undo, this, QOverload<>::of(&ScreenshotWindow::Undo));
    connect(&m_screenshotTool, &ScreenshotTool::Redo, this, QOverload<>::of(&ScreenshotWindow::Redo));
    m_picture.setParentWidgetRect(rect());
    emit screenshotToolWidgetShow(false);

    //connect(&m_screenshotTool, &ScreenshotTool::ShowWindow, &m_drawRectProperty, &CDrawProperty::ShowProperty);
    //connect(&m_screenshotTool, &ScreenshotTool::HideWindow, &m_drawRectProperty, &CDrawProperty::HideProperty);
    connect(&m_drawLineProperty, &CDrawProperty::PropertyChange, this, &ScreenshotWindow::PropertyChange);
    connect(&m_drawRectProperty, &CDrawProperty::PropertyChange, this, &ScreenshotWindow::PropertyChange);
    connect(&m_drawTextProperty, &CDrawProperty::PropertyChange, this, &ScreenshotWindow::PropertyChange);
    m_property.penColor = QColor(255, 0, 0);
    m_property.penWidth = 1;

    m_colorPicker.SetScreenCapture(m_screenWindow.screenPixmap);
    m_colorPicker.setVisible(false);

    m_screenshotTool.EnableUndo(false);
    m_screenshotTool.EnableRedo(false);
    m_screenshotTool.installEventFilter(this);
    activateWindow();
    //刷新定时器
    m_nUpdateTimer = startTimer(1000);
}

QPoint ScreenshotWindow::adjustScreenshotToolPos()
{
    QPoint pt = m_picture.rect().bottomRight();
    pt.setX(pt.x()-m_screenshotTool.width());
    pt.setY(pt.y() + m_picture.frameWidth()*2+g_screenShotToolSpacing);
    QPoint ptBottom(pt.x(), pt.y()+m_screenshotTool.height());
    if (!rect().contains(ptBottom))
    {
        pt.setY(rect().bottom()-m_screenshotTool.height());
    }
    return pt;
}

void ScreenshotWindow::calcRectPoint(QPoint &topLeft)
{
    if (m_mousePressPos == m_mouseReleasePos)
    {
        return;
    }
    //需要处理1.左下->右上 2.右上->左下 3.右下->左上
    if (m_mousePressPos.y() >= m_mouseReleasePos.y())
    {
        if (m_mousePressPos.x() <= m_mouseReleasePos.x())
        {
            topLeft.setY(m_mouseReleasePos.y());
        }
        else
        {
            topLeft = m_mouseReleasePos;
        }
    }
    else
    {
        if (m_mousePressPos.x() > m_mouseReleasePos.x())
        {
            topLeft.setX(m_mouseReleasePos.x());
        }
    }
}

int ScreenshotWindow::detectCusor(const QPoint &pt, int &dir) const
{
    return m_picture.detectCursor(pt, dir);
}

Shape *ScreenshotWindow::createShape(int shape)
{
    Shape* pShape = nullptr;
    switch (shape) {
    case Shape::line:
        pShape = new Line(this, m_property.penColor, m_property.penWidth);
        break;
    case Shape::rect:
        pShape = new Rect(this, m_property.penColor, m_property.penWidth);
        break;
    case Shape::text:
        pShape = new LineText(this, m_property.penColor, m_property.font);
    }

    return pShape;
}

PosQuadrant ScreenshotWindow::CheckPickerPos(const QPoint &pos)
{
    //计算取色器窗口是否超出屏幕，超出后重新计算显示位置
    int nColorPickerWidth = m_colorPicker.width();
    int nColorPickerHeight = m_colorPicker.height();
    //重新计算位
    //判断当前取色器位置在哪个象限
    switch (m_curQuadrant) {
        case PosQuadrant::leftTop:
        {
            //如果在坐上计算位置
            int x = pos.x() - nColorPickerWidth - 5;
            int y = pos.y() - nColorPickerHeight - 5;
            //在左上只需要判断左和上
            if (IsLeftBorder(x, rect()) && IsTopBorder(y, rect()))
            {
                //如果左上超出屏幕，则向右下显示
                m_curQuadrant = PosQuadrant::rightBottom;
                return m_curQuadrant;
            }
            else if (IsLeftBorder(x, rect()))
            {
                //如果左侧超出屏幕，则向右显示
                m_curQuadrant = PosQuadrant::rightTop;
                return m_curQuadrant;
            }
            else if (IsTopBorder(y, rect()))
            {
                //如果上方超出屏幕，则向下显示
                m_curQuadrant = PosQuadrant::leftBottom;
                return m_curQuadrant;
            }
        }
            break;
        case PosQuadrant::leftBottom:
        {
            //如果在左下计算位置
            int x = pos.x() - nColorPickerWidth - 5;
            int y = pos.y() + nColorPickerWidth + 5;
            //在左下只需要判断左和下
            if (IsLeftBorder(x, rect()) && IsBottomBorder(y, rect()))
            {
                //如果左下超出屏幕，则向右上显示
                m_curQuadrant = PosQuadrant::rightTop;
                return m_curQuadrant;
            }
            else if (IsLeftBorder(x, rect()))
            {
                //如果左侧超出屏幕，则向右显示
                m_curQuadrant = PosQuadrant::rightBottom;
                return m_curQuadrant;
            }
            else if (IsBottomBorder(y, rect()))
            {
                //如果下方超出屏幕，则向上显示
                m_curQuadrant = PosQuadrant::leftTop;
                return m_curQuadrant;
            }
        }
            break;
        case PosQuadrant::rightTop:
        {
            //如果在右上计算位置
            int x = pos.x() + nColorPickerWidth + 5;
            int y = pos.y() - nColorPickerHeight - 5;
            //在右上只需要判断右和上
            if (IsRightBorder(x, rect()) && IsTopBorder(y, rect()))
            {
                //如果右上超出屏幕，则向左下显示
                m_curQuadrant = PosQuadrant::leftBottom;
                return m_curQuadrant;
            }
            else if (IsRightBorder(x, rect()))
            {
                //如果右侧超出屏幕，则向左显示
                m_curQuadrant = PosQuadrant::leftTop;
                return m_curQuadrant;
            }
            else if (IsTopBorder(y, rect()))
            {
                //如果上方超出屏幕，则向下显示
                m_curQuadrant = PosQuadrant::rightBottom;
                return m_curQuadrant;
            }
        }
            break;
        case PosQuadrant::rightBottom:
        {
            //如果在右下计算位置
            int x = pos.x() + nColorPickerWidth + 5;
            int y = pos.y() + nColorPickerHeight + 5;
            //在右下只需要判断右和下
            if (IsRightBorder(x, rect()) && IsBottomBorder(y, rect()))
            {
                //如果右下超出屏幕，则向左上显示
                m_curQuadrant = PosQuadrant::leftTop;
                return m_curQuadrant;
            }
            else if (IsRightBorder(x, rect()))
            {
                //如果右侧超出屏幕，则向左显示
                m_curQuadrant = PosQuadrant::leftBottom;
                return m_curQuadrant;
            }
            else if (IsBottomBorder(y, rect()))
            {
                //如果下方超出屏幕，则向上显示
                m_curQuadrant = PosQuadrant::rightTop;
                return m_curQuadrant;
            }
        }
            break;
    }

    return m_curQuadrant;
}

void ScreenshotWindow::TextEditComplete()
{
    if (m_pShape && Shape::text == m_pShape->Type())
    {
        LineText *pLineText = static_cast<LineText*>(m_pShape);
        if (pLineText->TextLength() <= 0)
        {
            m_Shapes.removeAll(m_pShape);
            delete m_pShape;
            m_pShape = nullptr;
        }
        else
        {
            pLineText->SetEdit(false);
            m_pShape = nullptr;
        }
    }
    update();
}
